<template>
<div>
    <!--搜索栏-->
    <el-form :inline="true" :model="formInline" class="user-search">
        <el-form-item label="搜索：">
            <el-select v-model="formInline.type" placeholder="请选择类型">
                <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-date-picker type="date" placeholder="选择日期" v-model="formInline.statisticDate" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="getData">搜索</el-button>
        </el-form-item>
        <el-form-item>
            <el-button size="small" type="primary" icon="el-icon-search" @click="exportExcel">导出</el-button>
        </el-form-item>
    </el-form>

    <!--列表-->
    <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">
        <el-table-column  align="center"  sortable prop="type" label="类型"></el-table-column>
        <el-table-column  align="center"  sortable prop="materialName" label="材料名称"></el-table-column>
        <el-table-column  align="center"  sortable prop="amount" label="数量"></el-table-column>
        <el-table-column  align="center"  sortable prop="unit" label="单位"></el-table-column>
        <el-table-column  align="center"  sortable prop="createTime" label="时间"></el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
</div>
</template>

<script>
import * as api from '../../api/interface'
import Pagination from '../../components/Pagination'
export default {
    data() {
        return {
            loading: false, //是显示加载
            //查询条件
            formInline: {
                page: 1, //当前页面
                limit: 10, //每页数量
                type: '',
                //初始化为null
                statisticDate: null,
            },
            listData: [], //用户数据
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10
            },
            types: [
                { value: "", label: "请选择" },
                { value: "领用", label: "领用" },
                { value: "销售", label: "销售" }
            ],
            totalUse: 0,
            totalGet: 0
        }
    },
    // 注册组件
    components: {
        Pagination
    },
    /**
     * 页面初始化方法
     */
    created() {
        this.getData()
    },
    methods: {
        formatBillType: function (row, column) {
            return row.billType == '1' ? "销售" :
                row.billType == "2" ? "采购" :
                row.billType == "3" ? "发工资" :
                "未知";
        },
        // 获取列表数据
        getData() {
            this.loading = true
            let para = {
                current: this.formInline.page,
                size: this.formInline.limit,
                type: this.formInline.type,
                //作为参数传递到后端
                statisticDate: this.formInline.statisticDate
            }
            api.materialStatistic(para).then(data => {
                this.logining = false;
                if (data.message != "success") {
                    this.logining = false;
                    this.$message.error(data.message)
                } else {
                    this.loading = false
                    this.listData = data.returnPage.records
                    this.pageparm.currentPage = data.returnPage.current
                    this.pageparm.pageSize = data.returnPage.size
                    this.pageparm.total = data.returnPage.total

                    this.totalGet = 0;
                    this.totalUse = 0;
                    this.listData.forEach(item => {
                        if (item.type == "领用") {
                            this.totalGet += parseFloat(item.amount)
                        } else {
                            this.totalUse += parseFloat(item.amount)
                        }
                    })
                }
            }).catch(e => {
                this.logining = false;
            });
        },
        // 分页插件事件
        callFather(parm) {
            this.formInline.page = parm.currentPage
            this.formInline.limit = parm.pageSize
            this.getData()
        },
        //显示添加界面
        handleAdd: function (index, row) {
            this.editFormVisible = true
            this.title = '新增'
            this.editForm = {}
        },
        //显示编辑界面
        handleEdit: function (index, row) {
            this.editFormVisible = true
            this.title = '编辑'
            this.editForm = row
        },
        // 关闭编辑
        closeDialog() {
            this.editFormVisible = false
        },
        // 编辑、增加页面保存方法
        submitForm(editData) {
            this.$refs[editData].validate(valid => {
                if (valid) {
                    let para = Object.assign({}, this.editForm);
                    this.loading = true;
                    api.updateSaleLog(para)
                        .then(res => {
                            this.loading = false;
                            if (res.message == 'success') {
                                this.$message({ message: "提交成功", type: "success" });
                                this.getData();
                                this.editFormVisible = false;
                            } else {
                                this.$message({ type: 'error', message: res.message })
                            }
                        })
                        .catch(e => {
                            // this.editFormVisible = false
                            this.loading = false
                        })
                } else {
                    return false
                }
            })
        },
        // 删除
        handleDel(index, row) {
            this.$confirm('确定要删除吗?', '信息', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
                .then(() => {
                    let para = {
                        userId: row.userId
                    }
                    api.delSaleLog(para)
                        .then(res => {
                            if (res.message == 'success') {
                                this.$message({ message: "删除成功", type: "success" });
                                this.getData();
                            } else {
                                this.$message({ type: 'error', message: res.message })
                            }
                        })
                        .catch(e => {
                            this.loading = false
                        })
                });
        },
        exportExcel: function () {
            require.ensure([], () => {
                const {
                    export_json_to_excel
                } = require('../../assets/js/Export2Excel');
                const tHeader = ['类型', '材料名称', '数量', '单位', '时间']; //对应表格输出的title
                const filterVal = ['type', 'materialName', 'amount', 'unit', 'createTime']; // 对应表格输出的数据

                let para = {
                    current: 1,
                    size: 9999999,
                    type: this.formInline.type,
                    statisticDate: this.formInline.statisticDate
                }
                api.materialStatistic(para).then(data => {
                    let dataList = data.returnPage.records;
                    const exceldata = this.formatJson(filterVal, dataList)
                    export_json_to_excel(tHeader, exceldata, '食材领用消耗统计' + this.formInline.statisticDate)
                }).catch(e => {
                    console.log(e);
                });
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]))
        },
        dateFormat(fmt, date) {
            let ret;
            const opt = {
                "Y+": date.getFullYear().toString(), // 年
                "m+": (date.getMonth() + 1).toString(), // 月
                "d+": date.getDate().toString(), // 日
                "H+": date.getHours().toString(), // 时
                "M+": date.getMinutes().toString(), // 分
                "S+": date.getSeconds().toString() // 秒
                // 有其他格式化字符需求可以继续添加，必须转化成字符串
            };
            for (let k in opt) {
                ret = new RegExp("(" + k + ")").exec(fmt);
                if (ret) {
                    fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
                };
            };
            return fmt;
        }
    }
}
</script>

<style scoped>
.user-search {
    margin-top: 20px;
}
</style>
